<?php

namespace App\Models;

use DB;

class WaterBillOrder extends BaseModel
{
    protected $table = "waterbill_order";

    protected $rules = [
        'order_sn' => 'required',
        'admin_id' => 'required',
        'shop_id' => 'required',
        'mid' => 'required',
        'waterbill_id' => 'required',
        'goods_id' => 'required',
        'goods_name' => 'required',
        'goods_price' => ['required', 'numeric', 'regex:/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/'],
        'order_amount' => ['required', 'numeric', 'regex:/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/'],
        'title' => 'required',
        'buy_num' => 'required|numeric',
        'gift_num' => 'required|numeric',
        'total_num' => 'required|numeric',
        'rest_num' => 'required|numeric|same:total_num',
    ];

    protected $message = [
        'order_sn.required' => '订单号获取失败',
        'admin_id.required' => '商户ID获取失败',
        'shop_id.required' => '店铺ID获取失败',
        'mid.required' => '用户ID获取失败',
        'waterbill_id.required' => '水票ID获取失败',
        'goods_id.required' => '商品ID获取失败',
        'goods_name.required' => '商品名称获取失败',
        'goods_price.required' => '商品价格获取失败',
        'goods_price.numeric' => '商品价格必须是纯数字',
        'goods_price.regex' => '商品价格不能小于0',
        'order_amount.required' => '订单总价格获取失败',
        'order_amount.numeric' => '订单总价格必须是纯数字',
        'order_amount.regex' => '订单总价格不能小于0',
        'title.required' => '水票套餐信息获取失败',
        'buy_num.required' => '购买数量获取失败',
        'buy_num.numeric' => '购买数量必须是纯数字',
        'gift_num.required' => '赠送数量获取失败',
        'gift_num.numeric' => '赠送数量必须是纯数字',
        'total_num.required' => '总数量获取失败',
        'total_num.numeric' => '总数量必须是纯数字',
        'rest_num.required' => '剩余总数量获取失败',
        'rest_num.numeric' => '剩余总数量必须是纯数字',
        'rest_num.same' => '总数量与剩余总数量不一致',
    ];
//0.全部 1:已付款  2.未付款 3.微信支付 4.货到付款
    public $listType = [
        0 => '全部',
        1 => '已付款',
        2 => '未付款',
        3 => '微信支付',
        4 => '货到付款',
    ];

    public function waterBill()
    {
        return $this->hasOne('App\Models\WaterBill', 'id', 'waterbill_id');
    }

    public function member()
    {
        return $this->belongsTo('App\Models\Member', 'mid', 'id');
    }

    public function address()
    {
        return $this->hasOne('App\Models\Address', 'mid', 'mid');
    }

    public function getListByMid($mid)
    {
        $where['mid'] = $mid;
        $where['status'] = 1;
        $fields = 'id,mid,goods_id,goods_name,rest_num,admin_id';
        $rows = $this->_getList($where, $fields)->toArray();
        return $rows;
    }

    public function getOwnOrderList($shopId)
    {
        $keyword = request('keyword');
        $mid = request('mid');
        $start = request('time-start');
        $end = request('time-end');
        if(!is_administrator()) {
            $where['admin_id'] = plat_admin_id();
        } else {
            $where = [];
        }
        if ($shopId) {
            $where['shop_id'] = $shopId;
        }
        $type = intval(request('type', 0));
        //type 0.全部 1:已付款  2.未付款 3.微信支付 4.货到付款
        switch ($type) {
            case 1 :
                $where['pay_status'] = 20;
                break;
            case 2 :
                $where['pay_status'] = 10;
                break;
            case 3 :
                $where['type'] = 0;
                break;
            case 4 :
                $where['type'] = 1;
                break;
            default:
        }
        $keyword && $where['order_sn'] = ['like', '%' . $keyword . '%'];
        $mid && $where['mid'] = $mid;
        if ($start && !$end) {
            $timeArea = [strtotime($start), strtotime($start) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($end && !$start) {
            $timeArea = [strtotime($end), strtotime($end) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $timeArea[1] += 86399;
            $where['addtime'] = ['between', $timeArea];
        }
        $orderFields = 'id,admin_id,shop_id,order_sn,created_at,order_amount,mid,goods_id,goods_name,goods_price,title,buy_num,gift_num,total_num,description,type,pay_status';
        $memberFields = 'id,name,mobile,area_info,address';
        $addressFields = 'id,mid,name,mobile,area_info,address';
        $rows = $this->_getJoinTwoPageList('member', 'address', $where, $orderFields, ['id' => 'desc'], 10, 10, $memberFields, [], $addressFields, ['is_default' => 1]);
        $txtStr['pay_status'] = [10 => '未付款', 20 => '已付款', 0 => '已取消'];
        $txtStr['type'] = [0 => '微信支付', 1 => '货到付款'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }


    public function checkData($ids)
    {
        if (!$ids) {
            $this->error = '参数错误';
            return false;
        }

        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['goods_id'] = ['in', $ids];
        $where['shop_id'] = request('shop_id');
        $res = $this->_getList($where);
        if ($res) {
            return false;
        }
        return true;
    }

    public function addOrder()
    {
        $admin_id = $GLOBALS['admin_id'];
        $shop_id = $GLOBALS['shop_id'];
        $mid = $GLOBALS['mid'];
        $key = 'order_' . $admin_id . '_' . $shop_id . '_' . $mid;
        if ($this->redis->exists($key)) {
            $this->error = '请勿重复提交订单！';
            return false;
        }
        if (!($mid && $admin_id && $shop_id && request('waterbill_id') && request('bill_id'))) {
            $this->error = '非法操作！';
            return false;
        }
        $data['order_sn'] = makeOrderSn($mid);
        $data['admin_id'] = $admin_id;
        $data['shop_id'] = $shop_id;
        $data['mid'] = $mid;
        $data['type'] = request('type');
        $data['waterbill_id'] = request('waterbill_id');//waterbill_id 店铺水票ID   bill_id 套餐ID
        $waterBill = new WaterBill();
        $info = $waterBill->_getOneById($data['waterbill_id']);
        foreach ($info['waterbill_category'] as $v) {
            if ($v['id'] == request('bill_id')) {
                $data['title'] = $v['title'];
                $data['buy_num'] = $v['buy_num'];
                $data['gift_num'] = $v['gift_num'];
                $data['total_num'] = $v['total_num'];
                $data['description'] = $v['description'];
            }
        }
        $data['category_id'] = $info['category_id'];
        $data['brand_id'] = $info['brand_id'];
        $data['bucket_category_id'] = $info['bucket_category_id'];
        $data['shop_goods_id'] = $info['shop_goods_id'];
        $data['goods_id'] = $info['goods_id'];
        $data['goods_name'] = $info['goods_name'];
        $data['goods_price'] = $info['goods_price'];
        $data['order_amount'] = $data['buy_num'] * $info['goods_price'];
        $data['rest_num'] = $data['total_num'];
        $data['addtime'] = time();
        if (!$this->_validate($data)) {
            return false;
        }
        $this->_start();
        try {
            $res = $this->_save($data);
//            if (!$res) {
//                $this->_rollBack();
//                $this->error = '保存水票订单信息失败！';
//                return false;
//            }
            $data['id'] = $res;
            //更新用户水票数据
            $memberWaterBill = new MemberWaterBill();
            if ($data['type']) {
                $res = $memberWaterBill->addorUpdate($data);
//                if (!$res) {
//                    $this->_rollBack();
//                    $this->error = '更新用户水票数据失败！';
//                    return false;
//                }
                //记录水票消费日志
                $billLog = new MemberWaterBillLog();
                $data['buyer_id'] = $data['mid'];
                $data['bill_id'] = $res['id'];
                $billLog->log($data, $data, 2);
            }
            $this->_commit();
            //储存表单提交状态
            $this->redis->setex($key, 5, 1);
            $memberWaterBill->_redisGenerateBillListByMid($mid);
            return $data;
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '生成订单失败，请稍后再试！';
            return false;
        }
    }


    public function dealOrder($order_sn)
    {
        if (!$order_sn) {
            $this->error = '非法操作';
            return false;
        }
        //修改数据库订单状态
        $order = $this->_getOne(['order_sn' => $order_sn]);
        if (!$order) {
            $this->error = '订单号不存在';
            return false;
        }
        $order = $order->toArray();
        if ($order['type'] == 0 && $order['pay_status'] == 10) {
            $data['id'] = $order['id'];
            $data['pay_status'] = 20;
            $data['payment_time'] = time();
            $this->_start();
            try {
                $a = $this->_save($data);
                if (!$a) {
                    $this->_rollBack();
                    $this->error = '更新水票订单状态失败！';
                    return false;
                }
                //更新水票销量
                $waterBill = new WaterBill();
                $b = $waterBill->_inc(['id' => $order['waterbill_id']], 'sale_num');
                if (!$b) {
                    $this->_rollBack();
                    $this->error = '更新水票销量失败！';
                    return false;
                }
                //更新店铺营业额
                $shop = new Shop();
                $shopData = [
                    'total_water_bill_num' => "`total_water_bill_num`+{$order['total_num']}",
                    'sale_money' => "`sale_money`+{$order['order_amount']}",
                ];
                $c = $shop->_updateOrigin(['id' => $order['shop_id']], $shopData);
                if (!$c) {
                    $this->_rollBack();
                    $this->error = '更新店铺营业额失败！';
                    return false;
                }
                //更新用户水票数据
                $memberWaterBill = new MemberWaterBill();
                $d = $memberWaterBill->addorUpdate($order);
                if (!$d) {
                    $this->_rollBack();
                    $this->error = $memberWaterBill->getError();
                    return false;
                }
                $memberWaterBill->_redisGenerateBillListByMid($order['mid']);
                //  记录水票消费日志
                $billLog = new MemberWaterBillLog();
                $order['buyer_id'] = $order['mid'];
                $order['bill_id'] = $order['waterbill_id'];
                $e = $billLog->log($order, $order, 1);
                if (!$e) {
                    $this->_rollBack();
                    $this->error = $billLog->getError();
                    return false;
                }

                // 计算提成 by YuFan
                $orderData = [
                    'buy_num' => $order['buy_num'],
                    'gift_num' => $order['gift_num'],
                    'total_amount' => $order['order_amount']
                ];
                (new MemberCommission())->commissionHandle($order['mid'], $order['shop_id'], $orderData,'购买水票');
                $this->_commit();

                $wxTpl = new WxTpl();
                $wxTpl->sendReceiveMsg($order, 2);
                return true;
            } catch (\Exception $e) {
                $this->_rollBack();
                if ($this->error == '') {
                    $this->error = '更新水票订单状态失败！';
                }
                return false;
            }
        }
        return true;
    }

    //删除未付款线上水票
    public function clear()
    {
        //超过30分钟未付款的线上订单
        $time = time() - 1800;
        $where['addtime'] = ['<=',$time];
        $where['type'] = 0;
        $where['pay_status'] = 10;
        $this->_del($where);
    }

}
